package com.yuzhitong.shapi.util;

import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yuzhitong.shapi.BuildConfig;
import a.a.a.MyApplication;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.bean.MovieBean;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Created by Brsya
 * CreateDate: 2022/3/25  10:31
 * Description:
 * app专用Util
 */
public class AppUtil {

    public static String handleSearchText(String searchUrl, String searchText) {

        if (searchText == null) {
            return null;
        }

        String searchTextTrim = searchText.trim();

        if (StringUtil.isUrl(searchTextTrim) || StringUtil.isIp(searchTextTrim)) {
            String url;
            if (searchTextTrim.indexOf("http://") != 0 && searchTextTrim.indexOf("https://") != 0) {
                url = "https://" + searchTextTrim;
            } else {
                url = searchTextTrim;
            }
            return url;
        }

        if (searchUrl != null) {
            int lastIndex = searchUrl.lastIndexOf("null");
            if (lastIndex == -1) {
                return searchUrl + searchText;
            }
            return searchUrl.substring(0, lastIndex) + searchText;
        } else {
            String url = MyApplication.aCache.getAsString(Contents.CACHE_KEY_SEARCH_URL);
            if (url == null) {
                return Contents.SEARCH_URL_BD + searchText;
            }
        }
        return null;
    }

    /**
     * 启动到应用商店app详情界面
     *
     * @param appPkg    目标App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public static boolean launchAppDetail(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) return false;

            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void backgroundAnimation(View view, int startColor, int endColor, long duration) {
        //创建动画,这里的关键就是使用ArgbEvaluator, 后面2个参数就是 开始的颜色,和结束的颜色.
        ValueAnimator colorAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), startColor, endColor);
        colorAnimator.addUpdateListener(animation -> {
            int color = (int) animation.getAnimatedValue();//之后就可以得到动画的颜色了
            view.setBackgroundColor(color);//设置一下, 就可以看到效果.
        });
        colorAnimator.setDuration(duration);
        colorAnimator.start();
    }

    public static void textColorAnimation(TextView view, int startColor, int endColor, long duration) {
        //创建动画,这里的关键就是使用ArgbEvaluator, 后面2个参数就是 开始的颜色,和结束的颜色.
        ValueAnimator colorAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), startColor, endColor);
        colorAnimator.addUpdateListener(animation -> {
            int color = (int) animation.getAnimatedValue();//之后就可以得到动画的颜色了
            view.setTextColor(color);//设置一下, 就可以看到效果.
        });
        colorAnimator.setDuration(duration);
        colorAnimator.start();
    }


    /**
     * 广告过滤判断
     *
     * @param url 需要加载的url
     * @return 是否过滤广告
     */
    public static boolean adFilter(Context context, String url) {
        if (BuildConfig.VERSION_CODE < 50) {
            return false;
        }
        FileInputStream fileInputStream = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            fileInputStream = context.openFileInput("adFilter");
            isr = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
            br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            if ((line = br.readLine()) != null) {
                sb.append(line);
            }
            List<String> adFilterArr = JSON.parseArray(sb.toString(), String.class);
            for (String s : adFilterArr) {
                if (url.contains(s)) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 更新广告过滤规则
     *
     * @param adFilterList 规则列表
     */
    public static void updateAdFilter(Context context, List<String> adFilterList) {
        FileOutputStream fileOutputStream = null;
        OutputStreamWriter orw = null;
        BufferedWriter bw = null;
        try {

            fileOutputStream = context.openFileOutput("adFilter", Context.MODE_PRIVATE);
            orw = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
            bw = new BufferedWriter(orw);
            String adFilterJson = JSON.toJSONString(adFilterList);
            bw.write(adFilterJson);
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (orw != null) {
                    orw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 拼接影视标签
     *
     * @param movieBean 影视实体类
     * @return 拼接的影视标签
     */
    public static String getMovieTagListStr(MovieBean movieBean) {
        return getMovieTagListStr(movieBean, true);
    }

    /**
     * 拼接影视标签
     *
     * @param movieBean 影视实体类
     * @return 拼接的影视标签
     */
    public static String getMovieTagListStr(MovieBean movieBean, boolean isShowYear) {
        StringBuilder sb = new StringBuilder();
        if (isShowYear) {
            if (!StringUtil.isEmpty(movieBean.getVideoYear())) {
                sb.append(movieBean.getVideoYear())
                        .append(" / ");
            }
        }
        if (!StringUtil.isEmpty(movieBean.getVideoArea())) {
            sb.append(movieBean.getVideoArea())
                    .append(" / ");
        }
        if (!StringUtil.isEmpty(movieBean.getVideoTag())) {
            sb.append(movieBean.getVideoTag())
                    .append(" / ");
        }
        if (!StringUtil.isEmpty(movieBean.getUpState())) {
            sb.append(movieBean.getUpState())
                    .append(" / ");
        }
        if (sb.length() > 2) {
            sb.delete(sb.length() - 3, sb.length());
        }
        return sb.toString();
    }
}
